package cn.com.chengmandian.bike.service.impl;

import cn.com.chengmandian.bike.model.EbMemberFace;
import cn.com.chengmandian.bike.mapper.EbMemberFaceMapper;
import cn.com.chengmandian.bike.model.EbMemberInfo;
import cn.com.chengmandian.bike.service.IEbMemberFaceService;
import cn.com.chengmandian.bike.service.IEbMemberInfoService;
import cn.com.chengmandian.core.common.constants.CommonConstant;
import cn.com.chengmandian.core.common.utils.HttpUtils;
import cn.com.chengmandian.core.web.exceptions.BadResponseException;
import cn.com.chengmandian.service.bike.constants.MemberFaceBusinessType;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.IdcardUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * <p>
 * 电单车运营-人脸认证记录 服务实现类
 * </p>
 *
 * @author AutoGenerator
 * @since 2024-03-11
 */
@Slf4j
@Service
public class EbMemberFaceServiceImpl extends ServiceImpl<EbMemberFaceMapper, EbMemberFace> implements IEbMemberFaceService {

    @Autowired
    private IEbMemberInfoService memberInfoService;

    @Override
    public EbMemberFace getNewAuthFaceRecord(Integer memberId) {
        return this.getOne(new LambdaQueryWrapper<EbMemberFace>()
                .eq(EbMemberFace::getMemberId, memberId)
                .eq(EbMemberFace::getResult, CommonConstant.ONE)
                .orderByDesc(EbMemberFace::getId)
                .last("limit 0,1"));
    }

    @Override
    public void userFaceAuth(String name, String idCard, String facePhotoBase64, String facePhotoUrl, Integer memberId, String phone, String faceAppCode, Integer businessType) {
        Assert.isTrue(StrUtil.isNotBlank(faceAppCode), "缺少人脸识别APP_CODE");
        String post = "https://jmfaceid.market.alicloudapi.com";
        String path = "/idcard-face/validate";
        Map<String, String> headers = new HashMap<>();
        headers.put("Authorization", "APPCODE " + faceAppCode);
        headers.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
        Map<String, String> bodys = new HashMap<>();
        bodys.put("facePhotoBase64", facePhotoBase64);
        bodys.put("facePhotoUrl", facePhotoUrl);
        bodys.put("idCardNo", idCard);
        bodys.put("name", name);
        EbMemberFace ebMemberFace = new EbMemberFace();
        ebMemberFace.setCreateTime(new Date());
        ebMemberFace.setMemberId(memberId);
        ebMemberFace.setMemberMobile(phone);
        ebMemberFace.setName(name);
        ebMemberFace.setIdCard(idCard);
        ebMemberFace.setFacePhoto(facePhotoUrl);
        ebMemberFace.setBusinessType(businessType);
        Integer requestResult = 200;
        String requestMsg = "";
        try {
            HttpResponse response = HttpUtils.doPost(post, path, "POST", headers, new HashMap<>(), bodys);
            int statusCode = response.getStatusLine().getStatusCode();
            requestResult = statusCode;
            if(statusCode != 200){
                throw new BadResponseException(statusCode + "：人脸识别失败");
            }
            // 解析响应数据
            Map<String, Object> authResponseMap = JSONObject.parseObject(EntityUtils.toString(response.getEntity()), Map.class);
            log.info("人脸识别参数:{}", JSONObject.toJSONString(authResponseMap));
            Integer responseCode = MapUtil.getInt(authResponseMap, "code");
            requestResult = responseCode;
            if(!responseCode.equals(Integer.valueOf(200))){
                throw new BadResponseException(MapUtil.getStr(authResponseMap, "msg"));
            }
            requestMsg = MapUtil.getStr(authResponseMap, "msg");
            String userAuthData = MapUtil.getStr(authResponseMap, "data");
            if(StrUtil.isBlank(userAuthData)) {
                throw new BadResponseException("不是本人骑行");
            }
            Map<String, Object> responseDataMap = JSONObject.parseObject(userAuthData, Map.class);
            ebMemberFace.setMsg(MapUtil.getStr(responseDataMap, "msg"));
            ebMemberFace.setIncorrect(MapUtil.getInt(responseDataMap, "incorrect"));
            if(ebMemberFace.getIncorrect() != null && ebMemberFace.getIncorrect().equals(Integer.valueOf(100))) {
                ebMemberFace.setResult(MapUtil.getInt(responseDataMap, "result"));
                ebMemberFace.setScore(BigDecimal.valueOf(MapUtil.getDouble(responseDataMap, "score")));
            }else {
                throw new BadResponseException(ebMemberFace.getMsg());
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.info("人脸识别认证失败:{}", e.getMessage());
            ebMemberFace.setRequestResult(requestResult);
            ebMemberFace.setRequestMsg(e.getMessage());
            this.save(ebMemberFace);
            throw new BadResponseException(e.getMessage());
        }
        ebMemberFace.setRequestResult(requestResult);
        ebMemberFace.setRequestMsg(requestMsg);
        this.save(ebMemberFace);
        if(ebMemberFace.getResult() != null && !ebMemberFace.getResult().equals(CommonConstant.ONE)) {
            throw new BadResponseException(518, ebMemberFace.getMsg());
        }
    }
}
